package com.example.stlink.activitys.fragmentChild.activityStuHome;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.stlink.R;
import com.example.stlink.configs.adapter.StuAddCourseAdapter;
import com.example.stlink.configs.onRecyclerViewItemClickListener;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.domain.Course;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseData;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class AllCourses extends AppCompatActivity {

    private RecyclerView lvAllCourse;
    private List<Course> coursesData;
    private StuAddCourseAdapter adapter;
    private ImageView abIvTitle;
    private SwipeRefreshLayout srlMyRefresh;

    private static Bundle bundle;
    private static Handler handler;

    private int page = 1;

    private int mCurrentColIndex = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_course);
        initView();
        refreshData();
    }


    /**
     * 初始化布局中相关事件
     */
    private void initView(){
        lvAllCourse = findViewById(R.id.lv_all_course_list);
        abIvTitle = findViewById(R.id.ab_iv_title);
        srlMyRefresh = findViewById(R.id.srl_my_refresh);
        srlMyRefresh.setColorSchemeColors(Color.parseColor("#ff0000"),Color.parseColor("#00ff00"));

    }


    /**
     * 刷新数据
     */
    public void refreshData(){

        coursesData = new ArrayList<>();
        adapter = new StuAddCourseAdapter(
                AllCourses.this,
                R.layout.card_course_stu,
                coursesData,
                0
        );
        LinearLayoutManager llm = new LinearLayoutManager(AllCourses.this);
        lvAllCourse.setLayoutManager(llm);
        lvAllCourse.setAdapter(adapter);

        bundle = getIntent().getExtras();
        handler = new Handler(Looper.getMainLooper()){
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                CourseData courseData = (CourseData) msg.obj;
                coursesData.addAll(courseData.getRecords());
                adapter.notifyDataSetChanged();
                System.out.println("size == " + adapter.getItemCount() + "................................");
            }
        };
        getAllCourseList(10);
        setListener();
    }

    /**
     * 添加点击事件
     */
    public void setListener(){
        adapter.setOnItemClickListener(new onRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
            }

            @Override
            public void onItemLongClick(RecyclerView parent, View view, int position) { }
        });
        abIvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        srlMyRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
                srlMyRefresh.setRefreshing(false);
            }
        });
    }

    /**
     * 用一个子线程进行网络请求
     * 刷新数据
     * @param page 页面
     */
    private void getAllCourseList(final int page){
        new Thread(new Runnable() {
            final String urlParam = ModelFieldConstants.SIZE + "=" + page + "&" +
                    ModelFieldConstants.CURRENT + "=" + "1";
            final String url = UrlConstants.ALL_COURSE + "?" + urlParam;
            @Override
            public void run() {
                new GetUrlParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {
                        System.out.println("courseDataBaseResponse.getData() = " + baseResponse.getData() + "...............");

                        //解析数据
                        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                        Object obj = baseResponse.getData();
                        LinkedTreeMap<String, String> courseDataMap = null;
                        if(obj instanceof LinkedTreeMap){
                            courseDataMap = (LinkedTreeMap<String, String>) obj;
                        }
                        //将LinkedTreeMap中字段映射到CourseData类中
                        String jsonString = gson.toJson(courseDataMap);
                        CourseData<Course> courseData = gson.fromJson(jsonString, new TypeToken<CourseData<Course>>() {}.getType());

                        System.out.println("courseData = " + courseData);

                        if(courseData != null){
                            Message message = new Message();
                            message.obj = courseData;
                            handler.sendMessage(message);
                        }else{
                            System.out.println("courseData: null " + "...............................");
                        }
                    }

                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) { }
                }.getConnect(url);
            }
        }).start();
    }

}
